//
//  ApplyMemberShopViewController.m
//  YongChuanTradingArea
//
//  Created by Vivian on 2017/9/28.
//  Copyright © 2017年 李冰. All rights reserved.
//

#import "ApplyMemberShopViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "DirectionButton.h"

#import "ApplySelectAreaController.h" // 选择省市区
#import "StoreCategoryPicker.h"

@interface ApplyMemberShopViewController ()<CLLocationManagerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *cityLabel;
@property (weak, nonatomic) IBOutlet UITextField *shopNameTF;
@property (weak, nonatomic) IBOutlet UITextField *shopAddTF;
@property (weak, nonatomic) IBOutlet UILabel *bigCateLabel;
@property (weak, nonatomic) IBOutlet UILabel *smallCateLabel;
@property (weak, nonatomic) IBOutlet UITextField *shopTelTF;
@property (weak, nonatomic) IBOutlet UITextField *bussinessTimeTF;
@property (weak, nonatomic) IBOutlet UITextField *telTF;
@property (weak, nonatomic) IBOutlet UITextField *CompanyNameTF;
@property (weak, nonatomic) IBOutlet UITextField *CompanyLegalTF;
@property (weak, nonatomic) IBOutlet UITextField *contactTF;
@property (weak, nonatomic) IBOutlet UITextField *bankBeginTF;
@property (weak, nonatomic) IBOutlet UITextField *bankNameTF;
@property (weak, nonatomic) IBOutlet UITextField *bankAccTF;
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;
@property (weak, nonatomic) IBOutlet DirectionButton *firstBtn;
@property (weak, nonatomic) IBOutlet UIImageView *firstImage;
@property (nonatomic, strong) NSString *firstImageId;
@property (weak, nonatomic) IBOutlet DirectionButton *secondBtn;
@property (weak, nonatomic) IBOutlet UIImageView *secondImage;
@property (nonatomic, strong) NSString *secondImageId;
@property (weak, nonatomic) IBOutlet DirectionButton *thridBtn;
@property (weak, nonatomic) IBOutlet UIImageView *thirdImage;
@property (nonatomic, strong) NSString *thirdImageId;
@property (weak, nonatomic) IBOutlet DirectionButton *forthBtn;
@property (weak, nonatomic) IBOutlet UIImageView *forthImage;
@property (nonatomic, strong) NSString *fourthImageId;

@property (weak, nonatomic) DirectionButton *currentBtn;

@property (nonatomic, strong) NSString *proviceId;
@property (nonatomic, strong) NSString *cityId;
@property (nonatomic, strong) NSString *countyId;

@property (nonatomic, strong) StoreCategoryModel *parentCate;
@property (nonatomic, strong) StoreCategoryModel *childCate;

// 位置服务
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) NSString *locationAddressName;
@property (nonatomic, strong) CLLocation *location;
@end

@implementation ApplyMemberShopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.agreeBtn setAttributedTitle:[self.agreeBtn.titleLabel.text changeColor:kMainColor range:NSMakeRange(self.agreeBtn.titleLabel.text.length - 6, 6)] forState:UIControlStateNormal];
    self.view.backgroundColor = kBgColor;
    self.firstBtn.spaceBetweenTitleAndImage = 10;
    self.secondBtn.spaceBetweenTitleAndImage = 10;
    self.thridBtn.spaceBetweenTitleAndImage = 10;
    self.forthBtn.spaceBetweenTitleAndImage = 10;
    // Do any additional setup after loading the view from its nib.
    if (self.isMember) {
        self.title = @"注册会员店";
    }else{
        self.title = @"注册企业合伙人";
    }
    
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = 1000;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
    
    if (_isAgain)
    {
        
        [LBNetworkingInstance requestGET:getMenberInfo parameters:@{@"id":[LBUserManage defaultManager].user_id} showHUD:YES success:^(id  _Nonnull responseObject, NSInteger code, NSString * _Nonnull message) {
           
            if (code == YCNetworkingStatusCodeSuccess)
            {
                UserModel *userModel = [UserModel yy_modelWithJSON:responseObject[@"Data"]];
                [LBUserManage defaultManager].userModel = userModel;
                
                self.shopNameTF.text = userModel.STOREITEM.name;
                self.shopAddTF.text = userModel.ADDRESS;
                
                HomeCategoryModel *big = [HomeCategoryModel new];
                big.Id = [userModel.STOREITEM.bigtype integerValue];
                big.Name = userModel.STOREITEM.bigtype_name;
                self.parentCate = big;
                StoreCategoryModel *small = [StoreCategoryModel new];
                small.Id = userModel.STOREITEM.smalltype;
                small.Name = userModel.STOREITEM.smalltype_name;
                self.childCate = small;
                self.shopTelTF.text = userModel.STOREITEM.tel;
                self.bussinessTimeTF.text = userModel.STOREITEM.business_time;
                self.telTF.text = userModel.MOBILE;
                self.CompanyNameTF.text = userModel.MEMBERNAME;
                self.CompanyLegalTF.text = userModel.HFAREN;
                self.contactTF.text = userModel.CONTACTPHONE;
                self.bankBeginTF.text = userModel.BANKUSER;
                self.bankNameTF.text = userModel.BANKNAME;
                self.bankAccTF.text = userModel.BANKNUMBER;
                self.proviceId = userModel.PROVIINCEID;
                self.cityId = userModel.CITYID;
                self.countyId = userModel.COUNTYID;
                NSString *address = [NSString stringWithFormat:@"%@%@%@", userModel.PROVIINCENAME, userModel.CITYNAME, userModel.COUNTYNAME];
                _cityLabel.text = address.length == 0 ? @"地区" : address;
                _bigCateLabel.text = userModel.STOREITEM.bigtype_name.length == 0 ? @"分类" : userModel.STOREITEM.bigtype_name;
                _smallCateLabel.text = userModel.STOREITEM.smalltype_name.length == 0 ? @"子分类" : userModel.STOREITEM.smalltype_name;
                
                for (UserModelImgList *list in userModel.ImgList) {
                    if ([list.imgtype isEqualToString:@"HYDYYZZZP"]) {
                        [_firstImage sd_setImageWithURL:[NSURL URLWithString:list.image]];
                    }
                    if ([list.imgtype isEqualToString:@"HYDSHLGZP"]) {
                        [_secondImage sd_setImageWithURL:[NSURL URLWithString:list.image]];
                    }
                    if ([list.imgtype isEqualToString:@"HYDMDZP"]) {
                        [_thirdImage sd_setImageWithURL:[NSURL URLWithString:list.image]];
                    }
                    if ([list.imgtype isEqualToString:@"HYDQTZZZP"]) {
                        [_forthImage sd_setImageWithURL:[NSURL URLWithString:list.image]];
                    }
                }
            }
        }];
        
    }
    
}

- (IBAction)cityBtnAction:(UIButton *)sender {
    [self resignAllTF];
    ApplySelectAreaController *vc = [ApplySelectAreaController new];
    WEAKSELF;
    vc.selectBlock = ^(NSString *provinceId, NSString *cityId, NSString *areaId, NSString *address) {
        
        weakSelf.proviceId = provinceId;
        weakSelf.cityId = cityId;
        weakSelf.countyId = areaId;
        weakSelf.cityLabel.text = address.length == 0 ? @"地区" : address;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)bigCateAction:(UIButton *)sender {
    [self resignAllTF];
    
    [LBNetworkingInstance requestGET:goodsCategory parameters:@{@"parentId" : @"0"} showHUD:YES success:^(id  _Nonnull responseObject, NSInteger code, NSString * _Nonnull message) {
        
        if (code == YCNetworkingStatusCodeSuccess)
        {
            WEAKSELF;
            StoreCategoryPicker *picker = [StoreCategoryPicker new];
            picker.arrayData = [NSArray yy_modelArrayWithClass:StoreCategoryModel.class json:responseObject[@"Data"]];
            picker.selectBlock = ^(StoreCategoryModel *model) {
                weakSelf.parentCate = model;
            };
            [picker show];
        }
        
    }];
    
//    StoreCategoryPicker *picker = [StoreCategoryPicker new];
//    picker.arrayData = [HomeCategoryModel defaultModels];
//    picker.selectBlock = ^(StoreCategoryModel *model) {
//        weakSelf.parentCate = model;
//    };
//    [picker show];

    
}
- (IBAction)smallCateAction:(UIButton *)sender {
    [self resignAllTF];
    if (!self.parentCate)
    {
        [MBProgressHUD showMessageWithOutIcon:@"请选择上一级分类"];
        return;
    }
    
    [LBNetworkingInstance requestGET:goodsCategory parameters:@{@"parentId" : [NSString stringWithFormat:@"%ld", self.parentCate.Id]} showHUD:YES success:^(id  _Nonnull responseObject, NSInteger code, NSString * _Nonnull message) {
        
        if (code == YCNetworkingStatusCodeSuccess)
        {
            WEAKSELF;
            StoreCategoryPicker *picker = [StoreCategoryPicker new];
            picker.arrayData = [NSArray yy_modelArrayWithClass:StoreCategoryModel.class json:responseObject[@"Data"]];
            picker.selectBlock = ^(StoreCategoryModel *model) {
                weakSelf.childCate = model;
            };
            [picker show];
        }
        
    }];
}

- (void)setParentCate:(StoreCategoryModel *)parentCate {
    _parentCate = parentCate;
    
    _bigCateLabel.text = _parentCate.Name ?: @"分类";
}

- (void)setChildCate:(StoreCategoryModel *)childCate {
    _childCate = childCate;
    
    _smallCateLabel.text = _childCate.Name ?: @"子分类";
}

- (IBAction)agreeAction:(UIButton *)sender {
    [self resignAllTF];
    sender.selected = !sender.selected;
}

- (IBAction)submitAction:(UIButton *)sender {
    [self resignAllTF];
    if (!_agreeBtn.selected)
    {
        [MBProgressHUD showMessageWithOutIcon:@"请阅读同意协议"];
        return;
    }
    UserModel *userModel = [LBUserManage defaultManager].userModel;
    for (UserModelImgList *list in userModel.ImgList) {
        if ([list.imgtype isEqualToString:@"HYDYYZZZP"]) {
            _firstImageId = list.ID;
        }
        if ([list.imgtype isEqualToString:@"HYDSHLGZP"]) {
            _secondImageId = list.ID;
        }
        if ([list.imgtype isEqualToString:@"HYDMDZP"]) {
            _thirdImageId = list.ID;
        }
        if ([list.imgtype isEqualToString:@"HYDQTZZZP"]) {
            _fourthImageId = list.ID;
        }
    }
    
    NSString *cId = userModel.ID;
    NSString *mType = (self.isMember ? @"2" : @"3");// 类型2：会员店，3：企业合伙人，4：个人合伙人
    NSString *sName = self.shopNameTF.text;
    NSString *saddress = self.shopAddTF.text;
    NSString *bigType = [NSString stringWithFormat:@"%ld", self.parentCate.Id];
    NSString *smallType = self.childCate.Id;
    NSString *sTelPhone = self.shopTelTF.text;
    NSString *busDate = self.bussinessTimeTF.text;
    NSString *cCellPhone = self.telTF.text;
    NSString *cName = self.CompanyNameTF.text;
    NSString *lawName = self.CompanyLegalTF.text;
    NSString *contactPhone = self.contactTF.text;
    NSString *bankUserName = self.bankBeginTF.text;
    NSString *bankName = self.bankNameTF.text;
    NSString *bankNumber = self.bankAccTF.text;
    NSString *proviceId = self.proviceId;
    NSString *cityId = self.cityId;
    NSString *countyId = self.countyId;
    NSString *imgIds = [NSString stringWithFormat:@"%@,%@,%@,%@", _firstImageId, _secondImageId, _thirdImageId, _fourthImageId];
    NSString *address = self.locationAddressName;
    NSString *xPoint = [NSString stringWithFormat:@"%f", self.location.coordinate.longitude];
    NSString *yPoint = [NSString stringWithFormat:@"%f", self.location.coordinate.latitude];
    
    if (!_firstImageId || !_secondImageId || !_thirdImageId || !_thirdImageId)
    {
        [MBProgressHUD showMessageWithOutIcon:@"请上传图片"];
        return;
    }
    
    if (mType.length == 0 || sName.length == 0 || saddress.length == 0 || bigType.length == 0 ||
        smallType.length == 0 || sTelPhone.length == 0 || busDate == 0 || cCellPhone.length == 0 ||
        cName.length == 0 || lawName.length == 0 || contactPhone.length == 0 || contactPhone.length == 0 ||
        bankName.length == 0 || bankUserName.length == 0 || bankNumber.length == 0 ||
        proviceId.length == 0)
    {

        [MBProgressHUD showMessageWithOutIcon:@"请输入完整信息"];
        return;
    }
    
    NSDictionary *params = NSDictionaryOfVariableBindings(cId, mType,sName,saddress,bigType,smallType,sTelPhone,busDate,cCellPhone,cName,lawName,contactPhone,bankName,bankUserName,bankNumber,proviceId,imgIds);
    
    NSMutableDictionary *mutableParams = params.mutableCopy;
    
    if (cityId)
    {
         [mutableParams setObject:cityId forKey:@"cityId"];
    }
    if (countyId)
    {
        [mutableParams setObject:countyId forKey:@"countyId"];
    }
    
    if (address)
    {
        [mutableParams setObject:address forKey:@"address"];
    }
    if (xPoint)
    {
        [mutableParams setObject:xPoint forKey:@"xPoint"];
    }
    if (yPoint)
    {
        [mutableParams setObject:yPoint forKey:@"yPoint"];
    }
    [LBNetworkingInstance requestGET:upgradeStore parameters:mutableParams.copy showHUD:YES success:^(id  _Nonnull responseObject, NSInteger code, NSString * _Nonnull message) {
        
        if (code == YCNetworkingStatusCodeSuccess)
        {
            [MBProgressHUD showMessageWithOutIcon:@"申请成功"];

            [self.navigationController popToRootViewControllerAnimated:YES];

//            [UIViewController toHome];

        }
        else
        {
            [MBProgressHUD showMessageWithOutIcon:responseObject[@"ResultMsg"]];
        }
    }];
}

- (void)resignAllTF{
    [self.shopNameTF resignFirstResponder];
    [self.shopAddTF resignFirstResponder];
    [self.shopTelTF resignFirstResponder];
    [self.bussinessTimeTF resignFirstResponder];
    [self.telTF resignFirstResponder];
    [self.CompanyNameTF resignFirstResponder];
    [self.CompanyLegalTF resignFirstResponder];
    [self.contactTF resignFirstResponder];
    [self.bankBeginTF resignFirstResponder];
    [self.bankNameTF resignFirstResponder];
    [self.bankAccTF resignFirstResponder];
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    
    if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        //        [self.locationManager startUpdatingLocation];
        [self.locationManager startUpdatingLocation];
    }
    else if(status == kCLAuthorizationStatusDenied)
    {
        [self _alertUserSetting];
    }
    else if (status == kCLAuthorizationStatusNotDetermined)
    {
        [self.locationManager requestWhenInUseAuthorization];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *currentLocation = locations.lastObject;
//    [LBUserManage defaultManager].location = currentLocation;
    self.location = currentLocation;
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count > 0)
         {
             CLPlacemark *place = [array objectAtIndex:0];
             //获取城市
             NSString *city = place.locality;
             if (!city)
             {
                 city = place.administrativeArea;
             }
             NSLog(@"location city %@  ",city);
             self.locationAddressName = [NSString stringWithFormat:@"%@%@%@%@%@", place.administrativeArea ?: @"", place.subAdministrativeArea ?: @"", city, place.thoroughfare ?: @"", place.subThoroughfare ?: @""];
         }
     }];
}
- (IBAction)firstImage:(DirectionButton *)sender {
    [self resignAllTF];
    _currentBtn = sender;
    [self editBtnClicked];
}
- (IBAction)secondImage:(DirectionButton *)sender {
    [self resignAllTF];
    _currentBtn = sender;
    [self editBtnClicked];
}
- (IBAction)thirdImage:(DirectionButton *)sender {
    [self resignAllTF];
    _currentBtn = sender;
    [self editBtnClicked];
}
- (IBAction)forthImage:(DirectionButton *)sender {
    [self resignAllTF];
    _currentBtn = sender;
    [self editBtnClicked];
}

- (void) _alertUserSetting {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示"  message:@"未授权定位服务，是否现在设置？" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        [alertVC dismissViewControllerAnimated:YES completion:nil];
    }];
    
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //        NSLog(@"%@", [NSURL URLWithString:UIApplicationOpenSettingsURLString]);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    
    [alertVC addAction:cancelAction];
    [alertVC addAction:sureAction];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
}

- (void)editBtnClicked{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择相片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"相册🌌" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        // 去更新图片
        [weakSelf chosePhoto:ChosePhotoTypeAlbum];
    }];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机📷" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        // 去更新图片
        [weakSelf chosePhoto:ChosePhotoTypeCamera];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    [alert addAction:album];
    [alert addAction:camera];
    [alert addAction:cancel];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

#pragma mark - 选择照片
- (void)chosePhoto:(ChosePhotoType)type
{
    UIImagePickerController *piker = [[UIImagePickerController alloc] init];
    piker.delegate = self;
    // 设置编辑模式
    piker.allowsEditing = YES;
    
    if (type == ChosePhotoTypeAlbum) {
        piker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }else if (type == ChosePhotoTypeCamera) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            piker.sourceType = UIImagePickerControllerSourceTypeCamera;
        }else{
            [MBProgressHUD showError:@"相机不可用😭"];
            return;
        }
    }
    [self presentViewController:piker animated:YES completion:^{
    }];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    UIImage *img = info[UIImagePickerControllerEditedImage];
    [self uploadImage:img];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void) uploadImage:(UIImage *) img {
    
    NSData *data = UIImageJPEGRepresentation(img, 1);
    NSString * imgStr = [data base64EncodedStringWithOptions:0];
    
    NSString *baseId = [LBUserManage defaultManager].userModel.ID;
    NSString *modularName = @"memberImg";
    NSString *busType = @"HYDYYZZZP";
    
    if (_currentBtn.tag == 101)
    {
        busType = @"HYDYYZZZP";
    }
    else if (_currentBtn.tag == 102)
    {
        busType = @"HYDSHLGZP";
    }
    else if (_currentBtn.tag == 103)
    {
        busType = @"HYDMDZP";
    }
    else if (_currentBtn.tag == 104)
    {
        busType = @"HYDQTZZZP";
    }
    UserModel *userModel = [LBUserManage defaultManager].userModel;
    NSMutableArray * array = @[].mutableCopy;
    for (UserModelImgList *list in userModel.ImgList) {
        if ([list.imgtype isEqualToString:busType]) {
            [array addObject:list.ID];
        }
    }
    NSString * delIds = @"";
    if (array.count > 0) {
        delIds = [array componentsJoinedByString:@","];
    }
    
    NSString *image = imgStr;
    
    [LBNetworkingInstance requestPOST:@"http://47.92.115.33:8181/FileUpService.asmx/uploadImage" parameters:NSDictionaryOfVariableBindings(baseId,modularName,busType,delIds,image) showHUD:YES headers:@{} progress:^(float progress) {
        
    } success:^(id  _Nonnull responseObject, NSInteger code, NSString * _Nonnull message) {
    
        [LBUserManage defaultManager].userModel = [UserModel yy_modelWithJSON:responseObject[@"Data"]];
        
        if (code == YCNetworkingStatusCodeSuccess)
        {
            if (_currentBtn.tag == 101)
            {
                _firstImage.image = img;
            }
            else if (_currentBtn.tag == 102)
            {
                _secondImage.image = img;
            }
            else if (_currentBtn.tag == 103)
            {
                _thirdImage.image = img;
            }
            else if (_currentBtn.tag == 104)
            {
                _forthImage.image = img;
            }
        }
        
    } failure:^(NSError * _Nonnull err) {
        [MBProgressHUD showError:@"图片上传失败 请重试！"];
    }];
}

@end
